package com.hfh.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author hfh
 * @Date 2022 09 13 15 37
 **/
public class Test2 {
    @Test
    public void server() throws Exception {
        ServerSocket ss = new ServerSocket(9999);

        Socket s =ss.accept();
        ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
        // EOFException,读到末尾读不到数据
        MovieKeyWord mkw = (MovieKeyWord) ois.readObject();

        System.out.println(mkw);

        FileInputStream fis = new FileInputStream("img.png");
        OutputStream os = s.getOutputStream();
        byte[] arr = new byte[1024];
        int len;
        while ((len= fis.read(arr))!=-1){
            os.write(arr,0,len);
        }

        os.close();
        fis.close();
        ois.close();
        s.close();
        ss.close();





    }

    @Test
    public void client() throws IOException {
        Socket s = new Socket(InetAddress.getLocalHost(),9999);

        MovieKeyWord mkw = new MovieKeyWord("友情", "灾难片", "80-150");
        ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
        oos.writeObject(mkw);
        // s.shutdownOutput();

        InputStream is = s.getInputStream();
        FileOutputStream fos = new FileOutputStream("aaa.png");
        byte[] arr = new byte[1024];
        int len;
        while ((len= is.read(arr))!=-1){
            fos.write(arr,0,len);
        }

        fos.close();
        is.close();
        oos.close();
        s.close();
    }
}

